import datetime
import time
import dataAnalyze


def getFmtDate():
    return time.strftime('%y%m%d', time.localtime())


def getFmtTime(toNum=False):
    t = time.strftime('%H%M', time.localtime())
    if toNum:
        t = timeToNum(t)
    return t


def strDateToDateObj(strDate):
    """
    :param strDate:such as 220419
    :return:
    """
    return datetime.date(*map(int, cut(strDate, 2)))


def timeToNum(t=''):
    """
    时间字符串转化为, 顺便检查一下
    :param t:
    :return:该时间到当天00:00经过的分钟数
    """
    try:
        h = int(t[:2])
        if len(t) != 4 or h not in range(0, 25):
            raise ValueError
        m = int(t[2:4])
        if m not in range(0, 60):
            raise ValueError
        num = h * 60 + m
        if num < 0 or num > 1440:
            raise ValueError
    except (ValueError, IndexError):
        raise ValueError(f'Time format error, wrong time: {t}')
    return num


def cut(obj, sec):
    # python切片的时候允许下标溢出
    return [obj[i:i + sec] for i in range(0, len(obj), sec)]


class CBJTimeRW:
    lastDate = '220401'
    lastTime = '0000'
    tempDataPath = './temp/'
    dataPath = './data/'
    tempFilePath = dataPath + 'tempData.txt'

    def __init__(self):
        with open(self.tempFilePath, 'r') as f:
            self.lastDate, self.lastTime = f.readline()[:-1].split(' ')
            self.tempLine = f.readline()

    def checkDateTime(self, d, t):
        """
        检查时间
        :param d:date
        :param t:time
        :return: raise exception or None
        """
        timeToNum(t)
        checked = datetime.datetime(*map(int, cut(d, 2)), *map(int, cut(t, 2)))
        last = datetime.datetime(*map(int, cut(self.lastDate, 2)), *map(int, cut(self.lastTime, 2)))
        if checked < last:
            raise ValueError("datetime error! cannot input expired datetime")

    def setTempData(self):
        with open(self.tempFilePath, 'w') as f:
            f.write(f"{self.lastDate} {self.lastTime}\n")
            f.write(self.tempLine)

    def setBreakPoint(self, endDate='', endTime='', comment=''):
        # 检查是否具备设置断点条件
        if self.tempLine == '':
            return
        # 如果为空则设置为当前时间
        endDate = getFmtDate() if endDate == '' else endDate
        endTime = getFmtTime() if endTime == '' else endTime
        # 隔天处理
        if self.lastDate != endDate:
            with open(f"{self.dataPath}{self.lastDate}.txt", 'a') as f:
                f.write(self.tempLine.format(startTime=self.lastTime, endTime='2400', comment=comment))
            self.lastTime = '0000'
        # 设置当天记录
        if endTime == self.lastTime:
            print("0 min forbidden")
            return
        with open(f"{self.dataPath}{endDate}.txt", 'a') as f:
            f.write(self.tempLine.format(startTime=self.lastTime, endTime=endTime, comment=comment) + '\n')
        # 最后处理
        self.lastDate = endDate
        self.lastTime = endTime
        self.tempLine = ''
        self.setTempData()

    def setLastStart(self, attributeNum: int, startDate='', startTime='', comment=''):
        """
        设置活动开始
        """
        print(startTime)
        # 转换到十六进制 去除0x 变成大写 保留四位(用0填充)
        attribute = hex(attributeNum)[2:].upper().zfill(4)
        # 如果为空则设置为当前时间
        startDate = getFmtDate() if startDate == '' else startDate
        startTime = getFmtTime() if startTime == '' else startTime
        # 先下一个断点 如果之前没有tempLine, 会自动取消
        self.setBreakPoint(endDate=startDate, endTime=startTime, comment=comment)
        # 如果成功设置断点之后, 二者应该相等
        # 如果没有成功设置断点, 表示上一条已经完成, 这时候需要保持其在五分钟之内
        if dataAnalyze.calTimeSeq(self.lastTime, startTime) % 1440 <= 5:
            startDate = self.lastDate
            startTime = self.lastTime
        else:
            print(self.lastTime)
            print(startTime)
            raise ValueError
        self.tempLine = f"{{startTime}}~{{endTime}} {attribute} {comment}{{comment}}"
        # 最后处理, 不要以为前两个被BreakPoint做过了, 如果从上一次开始, BreakPoint不会设置
        self.lastDate = startDate
        self.lastTime = startTime
        print(self.tempLine)
        self.setTempData()

    def setLastEnd(self, attributeNum: int, endDate='', endTime='', comment=''):
        """
        设置活动结束
        依赖start与breakpoint实现
        """
        # setEnd对之前的tempLine有覆盖作用
        self.tempLine = ''
        self.setLastStart(attributeNum=attributeNum, startDate=self.lastDate, startTime=self.lastTime, comment=comment)
        self.setBreakPoint(endDate=endDate, endTime=endTime)

    def readLastText(self):
        with open(f"{self.dataPath}{self.lastDate}.txt", 'r') as f:
            lines = f.readlines()
        with open(f"{self.tempFilePath}", 'r') as f:
            allLine = f.readlines()
            for line in allLine:
                lines.append(line)
        return lines


if __name__ == '__main__':
    # myWrite()
    # print(getFmtDate())
    # print(getFmtTime())
    # string = '1234567890'
    # str1 = string[0:4]
    a = CBJTimeRW()
    print(a.readLastText())
    # a = cut('220202', 2)
    # b = map(int, a)
    # d1 = datetime.date(*map(int, cut('220202', 2)))
    # d2 = datetime.date(*map(int, cut('220203', 2)))
    # d3 = d2 - d1
    # print(type(d3.days))
    # print(str(hex(48)))
    # with open('tempDataFilePath', 'r') as f:
    #     print(f)
    # a='abc cbs dsa'
    # b=a.split(' ')
    # c=
    # print(a.split(' '))
    # print(hex(12).upper())
    # "dads".strip()
    pass
